package sunbt.gistools.util;

import cn.hutool.core.io.FileUtil;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.referencing.CRS;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import sunbt.gistools.exception.BusinessException;
import sunbt.gistools.exception.enums.ErrorCodeEnum;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author sunbt
 * @version 1.0
 * @date 2025/7/17 15:50
 * <p>
 * ShapeFile工具类
 */
public class ShapeFileUtils {

    /**
     * 检查矢量的坐标系
     *
     * @param shapefilePath 矢量文件地址
     * @return epsg坐标
     */
    public static int extractEPSGCode(String shapefilePath) {
        File file = new File(shapefilePath);
        try {
            FileDataStore store = FileDataStoreFinder.getDataStore(file);
            SimpleFeatureSource featureSource = store.getFeatureSource();
            CoordinateReferenceSystem crs = featureSource.getInfo().getCRS();
            String epsgCode = CRS.lookupIdentifier(crs, true);
            store.dispose(); // Always good practice to close the datastore
            return Integer.parseInt(epsgCode.substring(5)); // EPSG:XXXX
        } catch (Exception e) {
            System.err.println("Failed to extract EPSG code: " + e.getMessage());
            throw new BusinessException(ErrorCodeEnum.BUSINESS_ERROR.getCode(), "矢量文件不存在prj文件，不能指定坐标系！");
        }
    }

    /**
     * 读取矢量文件的CPG文件
     *
     * @param shapefilePath 矢量文件地址
     * @return 字符编码
     */
    public static String readCpgFileEncoding(String shapefilePath) {
        // 获取不带扩展名的文件路径
        String baseFilePath = shapefilePath.substring(0, shapefilePath.lastIndexOf("."));

        // 尝试读取小写和大写后缀的.cpg文件
        String[] possibleCpgFiles = {baseFilePath + ".cpg", baseFilePath + ".CPG"};
        for (String cpgFilePath : possibleCpgFiles) {
            if (Files.exists(Paths.get(cpgFilePath))) {
                // 如果文件存在，尝试读取文件
                try (BufferedReader reader = new BufferedReader(new FileReader(cpgFilePath))) {
                    String encoding = reader.readLine(); // 读取第一行
                    if ("UTF-8".equalsIgnoreCase(encoding) || "GBK".equalsIgnoreCase(encoding)) {
                        return encoding;
                    } else {
                        return "GBK"; // 如果不是UTF-8或GBK，返回GBK
                    }
                } catch (IOException e) {
                    System.err.println("矢量CPG文件读取失败！" + e.getMessage());
                    throw new BusinessException(ErrorCodeEnum.BUSINESS_ERROR.getCode(), "矢量CPG文件读取失败!");
                }
            }
        }

        // 如果两个文件都不存在或无法读取，返回默认编码GBK
        return "GBK";
    }

    /**
     * 查找文件夹下的矢量文件
     *
     * @param file 文件夹地址
     * @return 矢量文件集合
     */
    public static List<String> findShpFiles(File file) {
        List<String> shpFiles = new ArrayList<>();

        if (file.isDirectory()) {
            File[] files = file.listFiles();

            if (files != null) {
                for (File f : files) {
                    shpFiles.addAll(findShpFiles(f));
                }
            }
        } else {
            String fileName = file.getName();
            String ext = FileUtil.extName(fileName);

            if ("shp".equalsIgnoreCase(ext)) {
                shpFiles.add(file.getAbsolutePath());
            }
        }

        return shpFiles;
    }

    /**
     * 指定文件夹创建CPG文件
     *
     * @param directoryPath 文件夹
     * @param fileName      文件名
     * @param content       编码内容
     */
    public static void createCpgFile(String directoryPath, String fileName, String content) {
        // 检查目录路径是否以文件分隔符结束，如果没有，则添加
        if (!directoryPath.endsWith(File.separator)) {
            directoryPath += File.separator;
        }

        // 创建File对象，代表要创建的文件
        File file = new File(directoryPath + fileName);

        try {
            // 创建文件
            if (file.createNewFile()) {
                System.out.println(fileName + " 文件已创建");
            } else {
                System.out.println(fileName + " 文件已存在");
            }

            // 使用BufferedWriter写入内容
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
                writer.write(content);
                System.out.println("成功写入内容到 " + fileName);
            }
        } catch (IOException e) {
            System.out.println("发生错误：" + e.getMessage());
            e.printStackTrace();
        }
    }




}
